﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Gman.Entity.Entities;
using Gman.WebApp.ServiceControllers;
using Gman.WebApp.Models;
using System.Web.Caching;
using System.Web.UI;
using Gman.WebApp.Controllers.Base;

namespace Gman.WebApp.Controllers
{
    public class MaterialController : BaseController
    {
        private List<MaterialBE> ListaMateriales = new List<MaterialBE>();
        private List<ProveedorBE> ListaProveedores = new List<ProveedorBE>();
        private static int AccionMaterial = 0;

        public ActionResult Index()
        {
            return View();
        }

        #region modulo Mantenimiento

        public ActionResult Nuevo(Guid id)
        {
            var cache = new CacheProvider();
            MaterialBE material = new MaterialBE();
            SedeBE sede = new SedeBE();
            UsuariosBE user = UsuarioActual();
            sede.IDEmp = user.IDEmp;

            var model = new MaterialModel(material, ListaMateriales);

            List<SedeBE> sedes = OperacionServiceController.ListarSede(sede).ToList();
            sedes.Insert(0, new SedeBE() { IDSede = 0, NomSede = "Seleccion ..." });
            model.Sedes = new SelectList(sedes, "IDSede", "NomSede", model.Sedes);
            model = CombosFamiCate(model);
            model.Action = "nuevo";
            
            cache.Set(model.ID.Value.ToString(), model);
            
            model.ToolBar = new ToolBarModel();


            return PartialView(@"~/Views/Material/AddEditMaterial.cshtml", model);
        }

        public ActionResult Buscar()
        {
            var cache = new CacheProvider();
            MaterialBE material = new MaterialBE();
            SedeBE sede = new SedeBE();
            UsuariosBE user = UsuarioActual();

            sede.IDEmp = user.IDEmp;
            material.IDEmp = user.IDEmp;
            var model = new MaterialModel(material, ListaMateriales);
            List<SedeBE> sedes = OperacionServiceController.ListarSede(sede).ToList();
            sedes.Insert(0, new SedeBE() { IDSede = 0, NomSede = "Seleccion ..." });

            model.Sedes = new SelectList(sedes, "IDSede", "NomSede", model.Sedes);

            model = CombosFamiCate(model);

            cache.Set(model.ID.Value.ToString(), model);

            model.Materiales.Clear();


            model.ToolBar = new ToolBarModel();
            model.Action = "buscar";
            AccionMaterial = 1;

            return View(@"~/Views/Material/editar.cshtml", model);
        }

        public ActionResult ObtenerMaterial(Guid id, Int64? idMaterial)
        {
            var cache = new CacheProvider();
            MaterialModel model = GetMaterialModel(id);
            model.Material.IDMaterial = idMaterial;
            model.Material = OperacionServiceController.ObtenerMaterial(model.Material);
            model.Material.LstProveedores = OperacionServiceController.ListaProveedoresXMaterial(model.Material).ToList();

            if (model.Material.IDMaterial.HasValue) {
                cache.Set(idMaterial.Value.ToString(), model.Material);
                model.Action = "ver";
            }

            return PartialView(@"~/Views/Material/AddEditMaterial.cshtml", model);
        }

        public ActionResult EditarMaterial(Guid id)
        {
            var cache = new CacheProvider();

            MaterialModel model = GetMaterialModel(id);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "editar";

            if(model.Material.IDMaterial != null)
                return PartialView(@"~/Views/Material/AddEditMaterial.cshtml", model);
            else
                return RedirectToAction("Buscar");
        }

        public JsonResult Save(Guid id)
        {
            try
            {
                UsuariosBE user = UsuarioActual();
                MaterialModel model = GetMaterialModel(id);

                if (model.Action == "nuevo")
                {
                    MaterialBE obj = new MaterialBE();
                    //obj.CodMate = "MA-" + (Li().Count + 1);
                    obj.IDSede = model.Material.IDSede;
                    obj.TipoMate = model.Material.TipoMate;
                    obj.FamiMate = model.Material.FamiMate;
                    obj.SubFamiMate = model.Material.SubFamiMate;
                    obj.CatMate = model.Material.CatMate;
                    obj.SubCatMate = model.Material.SubCatMate;
                    
                    obj.DescMate = model.Material.DescMate;
                    obj.UniMedMate = model.Material.UniMedMate;
                    obj.SaldActMate = model.Material.SaldActMate;
                    obj.CostoPromMate = model.Material.CostoPromMate;
                    obj.PrecPromMate = model.Material.PrecPromMate;
                    obj.StckMinMate = model.Material.StckMinMate;
                    obj.StckRepoMate = model.Material.StckRepoMate;
                 
                    obj.UsuReg = user.NomUsu;
                    obj.TermCnxReg = Environment.MachineName;
                    obj.EstadoMate = 1;
                    obj.IDEmp = user.IDEmp;

                    int resultado = OperacionServiceController.RegistrarMaterial(obj);


                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Material {0} se guardo exitosamente.",obj.DescMate));
                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }

                if (model.Action == "editar")
                {

                    model.Material.UsuMod = user.NomUsu;
                    model.Material.TermCnxMod = Environment.MachineName;

                    int resultado = OperacionServiceController.ActualizarMaterial(model.Material);
                    
                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Material {0} se guardo exitosamente.", model.Material.DescMate));
                    }

                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                     
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

 

        #endregion




        #region Modulo Stock Materiles
        public ActionResult ModoBuscarStock (){
            var cache = new CacheProvider();
            MaterialBE material = new MaterialBE();
            SedeBE sede = new SedeBE();
            UsuariosBE user = UsuarioActual();
            
            sede.IDEmp = user.IDEmp;
            var model = new MaterialModel(material, ListaMateriales);
            List<SedeBE> sedes = OperacionServiceController.ListarSede(sede).ToList();
            sedes.Insert(0, new SedeBE() { IDSede = 0, NomSede = "Seleccion ..." });
            
            model.Sedes = new SelectList(OperacionServiceController.ListarSede(sede), "IDSede", "NomSede", model.Sedes);
            model.Sedes = new SelectList(sedes, "IDSede", "NomSede", model.Sedes);

            model = CombosFamiCate(model);

            cache.Set(model.ID.Value.ToString(), model);
            model.ToolBar = new ToolBarModel();
            model.Action = "buscar";
            AccionMaterial = 0;

            return View(@"~/Views/Material/Stock.cshtml", model);
        }

        public ActionResult GetListaMaterial(Guid id)
        {
            MaterialModel model = GetMaterialModel(id);
            UsuariosBE user = UsuarioActual();
            model.Material.IDEmp = user.IDEmp;
            model.Materiales.Clear();
            model.Action = "buscar";

            List<MaterialBE> ListaMateriales = new List<MaterialBE>();
            ListaMateriales = OperacionServiceController.ListarStockMaterial(model.Material).ToList();

            foreach (MaterialBE m in ListaMateriales)
            {
                model.Materiales.Add(m);
            }

            if (AccionMaterial == 1)
                return PartialView(@"~/Views/Material/ListaMateriales.cshtml", model);
            else
                return PartialView(@"~/Views/Material/ListarMateriales.cshtml", model);
        }

        #endregion

        private MaterialModel CombosFamiCate(MaterialModel model) {


            List<SelectListItem> listTipo = new List<SelectListItem>();
            listTipo.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listTipo.Add(new SelectListItem() { Text = "Equipos", Value = "1" });
            listTipo.Add(new SelectListItem() { Text = "Maquinarias", Value = "2" });
            listTipo.Add(new SelectListItem() { Text = "Materiales Electricos", Value = "3" });
            listTipo.Add(new SelectListItem() { Text = "Herramientas", Value = "4" });
        
            List<SelectListItem> listFam = new List<SelectListItem>();
            listFam.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listFam.Add(new SelectListItem() { Text = "Electrico", Value = "1" });
            listFam.Add(new SelectListItem() { Text = "Seguridad", Value = "2" });
            listFam.Add(new SelectListItem() { Text = "Frio", Value = "3" });

            List<SelectListItem> listSubFam = new List<SelectListItem>();
            listSubFam.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listSubFam.Add(new SelectListItem() { Text = "Iluminacion", Value = "1" });
            listSubFam.Add(new SelectListItem() { Text = "Climatizacion", Value = "2" });
            listSubFam.Add(new SelectListItem() { Text = "Seguridad", Value = "3" });

            List<SelectListItem> listCate = new List<SelectListItem>();
            listCate.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listCate.Add(new SelectListItem() { Text = "Equipos", Value = "1" });
            listCate.Add(new SelectListItem() { Text = "Muebles", Value = "2" });
            listCate.Add(new SelectListItem() { Text = "Plataformas", Value = "3" });

            List<SelectListItem> listSubCate = new List<SelectListItem>();
            listSubCate.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listSubCate.Add(new SelectListItem() { Text = "Congeladoras", Value = "1" });
            listSubCate.Add(new SelectListItem() { Text = "Vitrinas", Value = "2" });
            listSubCate.Add(new SelectListItem() { Text = "Tablero de control", Value = "3" });

            model.Tipo = new SelectList(listTipo, "Value", "Text");
            model.Femilia = new SelectList(listFam, "Value", "Text");
            model.SubFemilia = new SelectList(listSubFam, "Value", "Text");
            model.Categoria = new SelectList(listCate, "Value", "Text");
            model.SubCategoria = new SelectList(listSubCate, "Value", "Text");

            return model;
        }

        private UsuariosBE UsuarioActual()
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                return user;
            }
            catch { return null; }
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            MaterialModel model = GetMaterialModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();

            var setter = new PropertySetter<MaterialModel>.SetterOptions();
            setter.objectToSet = model;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<MaterialModel>.SetFinalObject(setter);

            validationList.AddRange(new MaterialModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            MaterialModel model = GetMaterialModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> propertyChangeList = new List<KeyValuePair<string, string>>();

            validationList.AddRange(new MaterialModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList,
                PropertyVisibilityList = propertyChangeList
            });
        }

        public MaterialModel GetMaterialModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new MaterialModel(new MaterialBE(),new List<MaterialBE>());
                cache.Set(key, existingModel);
            }
            return (MaterialModel)existingModel;
        }

        public ActionResult GetListaStockMaterial(Guid id)
        {
            MaterialModel model = GetMaterialModel(id);
            MaterialBE m = new MaterialBE();

            return PartialView(@"~/Views/Sede/ListaPersonal.cshtml", model);
        }

        public ActionResult LoadAddOrEditProveedores(Guid id, Guid? proveedorGuid)
        {
            var cache = new CacheProvider();

                var materialModel = GetMaterialModel(id);
                
                materialModel.Proveedores = OperacionServiceController.ListProveedor(new ProveedorBE()).ToList();

                return PartialView(@"~/Views/material/Proveedores.cshtml", materialModel);
        }

        public ActionResult AgregarProveedor(Guid id, int idProveedor)
        {
            var cache = new CacheProvider();
            MaterialModel model = GetMaterialModel(id);
            List<ProveedorBE> lista = model.Proveedores;
            ProveedorBE proveedor = new ProveedorBE();
            foreach (var item in lista){
                if (item.IDProveedor == idProveedor) {
                    proveedor = item;
                    break;
                }
            }

            if (model.Material.LstProveedores == null)
            {
                model.Material.LstProveedores = ListaProveedores;
                model.Material.LstProveedores.Add(proveedor);
            }
            else {
                model.Material.LstProveedores.Add(proveedor);
            }


            return PartialView(@"~/Views/Material/Proveedores.cshtml", model);
        }

        public ActionResult QuitarProveedor(Guid id, int idProveedor)
        {
            var cache = new CacheProvider();
            MaterialModel model = GetMaterialModel(id);
            List<ProveedorBE> lista = model.Proveedores;
            ProveedorBE proveedor = new ProveedorBE();
            foreach (var item in model.Material.LstProveedores)
            {
                if (item.IDProveedor == idProveedor)
                {
                    model.Material.LstProveedores.Remove(item);
                    break;
                }
            }

            return PartialView(@"~/Views/Material/Proveedores.cshtml", model);
        }


    }
}
